const app = getApp();
const AJAX = app.$ajax,
  $wx = app.$wx;

Page({
  data: {
    administerStatus: 0
  },

  onLoad(){},

  onShow(){
    this.getCartList();
  },

  onShareAppMessage(){

  },

  administer(){
    let td = this.data;
    this.setData({
      administerStatus: td.administerStatus == 0 ? 1 : 0
    });
  },

  checkItem(e){
    let td = this.data,
        ed = e.currentTarget.dataset,
        goods_list = td.cartInfo.goods_list;

    AJAX.getStatus({
      loadType: 'default',
      loadMsg: '添加中...',
      goods_key: goods_list[ed.index].goods_key
    }).then(([status, res, msg]) => {
      if(status){
        td.cartInfo.goods_list[ed.index].is_check = !ed.status;
        this.setData({
          cartInfo: td.cartInfo
        });
        this.isCheckAll(td.cartInfo.goods_list);
      }else{
        $wx.showToast(msg);
      }
    });
   
  },

  checkAll(e){
    let td = this.data,
        ed = e.currentTarget.dataset;
    
    td.cartInfo.goods_list.map(item => item.is_check = !ed.status);
    this.setData({
      cartInfo: td.cartInfo,
      checkAll: !ed.status
    });
  },

  formSubmit(e){
    let td = this.data, 
        form_obj = e.detail.value, 
        goods_list = td.cartInfo.goods_list,
        goods_key = [];

    for (let i in form_obj) {
      if (form_obj[i]) {
        goods_key.push( goods_list[form_obj[i]].goods_key);
      }
    }

    if (td.administerStatus == 0){
      if (goods_key.length === 0) {
        $wx.showToast('请选择商品');
      } else {
        this.createOrder();
      }
    }else{
      this.deleteCartCommodity({
        goods_key: JSON.stringify(goods_key)
      });
    }
    
  },

  /*获取购物列表*/ 
  getCartList(){
    AJAX.getCartList({
      loadType: 'bar'
    }).then(([status, res, msg]) => {
      if(status){
        this.setData({
          cartInfo: res
        });
        this.isCheckAll(res.goods_list);
      }else{
        $wx.showToast(msg);
      }
    });
  },

  createOrder(){
    AJAX.createOrder({
      loadType: 'default',
      loadMsg: '加载中...',
      type: 1
    }).then(([status, res, msg]) => {
      if(status){
        wx.setStorageSync("orderDetail", res);
        wx.navigateTo({
          url: '/pages/subpage/order/detail/detail'
        })
      }else{
        $wx.showToast(msg);
      }
    });
  },

  deleteCartCommodity(params = {}){
    let _this = this;
    AJAX.deleteCartCommodity({
      loadType: 'default',
      loadMsf: '删除中...',
      ...params
    }).then(([status,res, msg]) => {
      $wx.showToast(msg, {
        success(){
          if(status){
            _this.getCartList();
          }
        }
      });
    });
  },

  isCheckAll(obj){
    let check_all = true;
    obj.map(item => {
      if(!item.is_check){
        check_all = false;
      }
    });

    this.setData({
      checkAll: obj.length > 0 ? check_all : false
    });
  }
});